#include "chooselevelscene.h"
#include <QMenuBar>
#include <QPainter>
#include "mypushbutton.h"
#include <QTimer>
#include <QLabel>

ChooseLevelScene::ChooseLevelScene(QWidget *parent) : QMainWindow(parent)
{
    // 配置选择关卡场景
    setFixedSize(320, 588);

    // 设置图标
    setWindowIcon(QPixmap(":/res/Coin0001.png"));

    // 设置标题
    setWindowTitle("选择关卡场景");

    // 创建菜单栏
    QMenuBar* bar = menuBar();
    setMenuBar(bar);

    // 创建开始菜单
    QMenu* startMenu = bar->addMenu("开始");

    // 创建退出 菜单项
    QAction* quitAction = startMenu->addAction("退出");

    // 点击退出 实现退出游戏
    connect(quitAction, &QAction::triggered, this, [=](){
        close();
    });

    // 返回按钮
    MyPushButton* backBtn = new MyPushButton(":/res/BackButton.png", ":/res/BackButtonSelected.png");
    backBtn->setParent(this);
    backBtn->move(width() - backBtn->width(), height() - backBtn->width());

    // 点击返回
    connect(backBtn, &MyPushButton::clicked, this, [=](){
        // 告诉主场景 我返回了 主场景监听ChooseLevelScene的返回按钮
        // 延时返回
        QTimer::singleShot(100, this, [=](){
            emit chooseSceneBack();
        });
    });

    // 创建选择关卡的按钮
    for (int i = 0; i < 20; ++i) {
        MyPushButton* menuBtn = new MyPushButton(":/res/LevelIcon.png");
        menuBtn->setParent(this);
        menuBtn->move(25 + i % 4 * 70, 130 + i / 4 * 70);

        connect(menuBtn, &MyPushButton::clicked, this, [=](){
            qDebug() << (QString("您选择了第 %1 关").arg(i +1));
            // 进入游戏场景
            hide();
            play = new PlayScene(i + 1);
            play->setGeometry(geometry());
            play->show();
            connect(play, &PlayScene::chooseSceneBack, this, [=](){
                show();
                delete play;
                play = nullptr;
            });
        });

        QLabel* label = new QLabel;
        label->setParent(this);
        label->setFixedSize(menuBtn->width(), menuBtn->height());
        label->setText(QString::number(i + 1));
        label->move(menuBtn->x(), menuBtn->y());
        label->setAlignment(Qt::AlignCenter);
        label->setAttribute(Qt::WA_TransparentForMouseEvents);
    }
}

void ChooseLevelScene::paintEvent(QPaintEvent*)
{
    QPainter painter(this);
    QPixmap pix;
    pix.load(":/res/OtherSceneBg.png");
    painter.drawPixmap(0, 0, width(), height(), pix);

    pix.load(":/res/Title.png");
    painter.drawPixmap((width() - pix.width()) * 0.5, 30, pix.width(), pix.height(), pix);
}
